package com.gmcc.aiquality.webadmin.upms.executor;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gmcc.aiquality.common.core.object.CallResult;
import com.gmcc.aiquality.common.core.object.TokenData;
import com.gmcc.aiquality.common.online.config.OnlineProperties;
import com.gmcc.aiquality.common.online.dto.OnlineFilterDto;
import com.gmcc.aiquality.common.online.model.OnlineTable;
import com.gmcc.aiquality.common.online.object.BaseOnlineExtendExecutor;
import com.gmcc.aiquality.common.online.util.OnlineDataSourceUtil;
import com.gmcc.aiquality.webadmin.upms.constants.TaskConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class DataCollectionTaskExtendExampleExecutor extends BaseOnlineExtendExecutor {

    @Autowired
    private OnlineProperties onlineProperties;

    @Autowired
    private OnlineDataSourceUtil onlineDataSourceUtil;

    @Override
    public void afterSelectOne(OnlineTable table, Map<String, Object> result) {
        super.afterSelectOne(table, result);
    }

    @Override
    public CallResult beforeUpdate(OnlineTable table, JSONObject data) {
        return super.beforeUpdate(table, data);
    }

    //自定义新增逻辑
    @Override
    public CallResult beforeInsertWithRelation(
            OnlineTable masterTable, JSONObject masterData, Map<OnlineTable, List<JSONObject>> slaveTableAndDataMap) {
        // 如果该配置项是true，说明所有的数据表操作都不在同一个事务内完成。
        if (BooleanUtil.isTrue(onlineProperties.getEnabledMultiDatabaseWrite())) {
            try {
                //获取创建人名称
                SaSession session = StpUtil.getTokenSession();
                TokenData tokenData = JSON.toJavaObject(
                        (JSONObject) session.get(TokenData.REQUEST_ATTRIBUTE_NAME), TokenData.class);
                String showName = tokenData.getShowName();
                //设置主键为UUID
                masterData.put("task_id", UUID.randomUUID().toString());
                //设置任务类型
                masterData.put("task_type", TaskConstants.DATA_TASK);
                //设置任务状态
                masterData.put("task_status", TaskConstants.RUNNING);
                //设置创建人
                masterData.put("task_creator", showName);
                //设置任务创建时间
                masterData.put("create_time", DateUtil.format(DateUtil.date(), "yyyy/MM/dd HH:mm:ss"));
                //拼接任务内容
                String projectCode = masterData.getString("project_code");
                String projectName = masterData.getString("project_name");
                String clientName = masterData.getString("client_name");
                String city = masterData.getString("city");
                String projectType = masterData.getString("project_type");
                String projectStatus = masterData.getString("project_status");
                String projectPhase = masterData.getString("project_phase");
                String projectProgress = masterData.getString("project_progress");
                String approvalMethod = masterData.getString("approval_method");
                String industry = masterData.getString("industry");
                JSONArray jsonArray = masterData.getJSONArray("created_start_time");
                String projectLevel = masterData.getString("project_level");

                // 使用StringBuilder条件拼接
                StringBuilder contentBuilder = new StringBuilder();
                if (projectName != null && !projectName.isEmpty()) {
                    contentBuilder.append("项目名称：").append(projectName);
                }
                if (projectCode != null && !projectCode.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("项目编码：").append(projectCode);
                }
                if (clientName != null && !clientName.isEmpty()) {
                    contentBuilder.append("客户名称：").append(clientName);
                }
                if (city != null && !city.isEmpty()) {
                    contentBuilder.append("地市：").append(city);
                }
                if (projectType != null && !projectType.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("项目类型：").append(projectType);
                }
                if (projectStatus != null && !projectStatus.isEmpty()) {
                    contentBuilder.append("项目状态：").append(projectStatus);
                }
                if (projectPhase != null && !projectPhase.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("项目阶段：").append(projectPhase);
                }
                if (projectProgress != null && !projectProgress.isEmpty()) {
                    contentBuilder.append("项目进度：").append(projectProgress);
                }
                if (approvalMethod != null && !approvalMethod.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("立项方式：").append(approvalMethod);
                }
                if (industry != null && !industry.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("所属行业：").append(industry);
                }
                if (projectLevel != null && !projectLevel.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("立项分级：").append(projectLevel);
                }
                if (jsonArray != null && !jsonArray.isEmpty()) {
                    if (!contentBuilder.isEmpty()) contentBuilder.append("；");
                    contentBuilder.append("创建时间范围：").append(jsonArray.getString(0)).append("-").append(jsonArray.getString(1));
                }
                String taskContent = contentBuilder.toString();
                masterData.put("task_content", taskContent);
                //TODO 定时任务/线程执行任务
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return CallResult.error(e.getMessage());
            }
        }
        return CallResult.ok();
    }




    //自定义查询逻辑
    @Override
    public void beforeSelectList(OnlineTable table, List<OnlineFilterDto> filterList) {
        String tableName = table.getTableName();
        //判断是否为任务管理查询
        if ((tableName !=null && tableName.equals("data_collection_task"))){
            String tableId = table.getTableId().toString();
            String taskType = switch (tableId) {
                case TaskConstants.ai_quality_task_id -> TaskConstants.AI_TASK;
                case TaskConstants.download_task_id -> TaskConstants.DOWN_TASK;
                default -> TaskConstants.DATA_TASK;
            };
            OnlineFilterDto filter = new OnlineFilterDto();
            filter.setColumnName("task_type");
            filter.setColumnValue(taskType);
            filterList.add(filter);
        }
    }

    /**
     * 表数据列表查询之后执行的操作。
     *
     * @param table      表对象。
     * @param resultList 查询结果。如果有修改，可直接在当前参数修改后即可生效。
     */
    @Override
    public void afterSelectList(OnlineTable table, List<Map<String, Object>> resultList) {
        String tableName = table.getTableName();
        //得到当前用户的基础信息
        TokenData tokenData = TokenData.takeFromRequest();
        Boolean isAdmin = tokenData.getIsAdmin();
        Long userId = tokenData.getUserId();
        String loginName = tokenData.getLoginName();
        Long deptId = tokenData.getDeptId();
        String deptName = tokenData.getDeptName();
        Integer userStatus = tokenData.getUserStatus();
        String  dataPermId= tokenData.getDataPermId();
        //判断是否为数据采集访问项目查询
        if ((tableName !=null && tableName.equals("task_project"))) {
            for (Map<String, Object> map : resultList) {
                String projectId = map.get("project_id").toString();
                String sqlStr = "select * from project where project_code = '" + projectId + "'";
                try {
                    List<Map<String, Object>> results = onlineDataSourceUtil.query(table.getDblinkId(), sqlStr);
                    if (CollUtil.isNotEmpty(results)) {
                        Map<String, Object> resultMap = results.get(0);
                        map.putAll(resultMap);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        if ((tableName !=null && tableName.equals("data_collection_task"))){
            for (Map<String, Object> map : resultList) {
                map.put("loginName",loginName);
                map.put("deptName",deptName);
                map.put("isAdmin",isAdmin);
                map.put("userId",userId);
                map.put("deptId",deptId);
                map.put("userStatus",userStatus);
                map.put("dataPermId",dataPermId);
                String taskId = map.get("task_id").toString();
                String sqlStr = "select * from  data_collection_task dct " +
                        "left join task_project tp on dct.task_id =tp.task_id " +
                        "left join project p on p.project_code  = tp.project_id " +
                        "left join qualityresult q on dct.task_id =q.task_id " +
                        "where dct.task_type  = 1 " +
                        "and dct.task_id = '" + taskId + "'";
                try {
                    List<Map<String, Object>> results = onlineDataSourceUtil.query(table.getDblinkId(), sqlStr);
                    if (CollUtil.isNotEmpty(results)) {
                        Map<String, Object> resultMap = results.get(0);
                        map.putAll(resultMap);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        //是否为AI质检任务查看结果查询
        if ((tableName !=null && tableName.equals("task_result"))) {
            for (Map<String, Object> map : resultList) {
                String projectId = map.get("result_id").toString();
                String sqlStr = "select * from qualityresult where id = '" + projectId + "'";
                try {
                    List<Map<String, Object>> results = onlineDataSourceUtil.query(table.getDblinkId(), sqlStr);
                    if (CollUtil.isNotEmpty(results)) {
                        Map<String, Object> resultMap = results.get(0);
                        map.putAll(resultMap);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}